from tortoise.expressions import Q
from app.core.crud import CRUDBase
from app.models.admin import Notices
from app.schemas.users import NoticesCreate,NoticesUpdate

class NoticesController(CRUDBase[Notices, NoticesCreate, NoticesUpdate]):
    def __init__(self):
        super().__init__(model=Notices)

    async def do_list(self, page: int, page_size: int, search: Q = Q()):
        query = self.model.filter(search)
        total = await query.count()
        objs =  await query.offset((page - 1) * page_size).limit(page_size).order_by('-id')
        data = [await obj.to_dict() for obj in objs]
        for item in data:
            if item['status']==1:
                item['status_name'] = "已处理"
            else:
                item['status_name'] = "待处理"
        return total, data

    async def do_detail(self,data_id:int):
        obj = await self.get(id=data_id)
        data = await obj.to_dict()
        return data

    async def do_create(self, obj_in: NoticesCreate):
        await self.create(obj_in=obj_in)
        return True

    async def do_update(self, obj_in: NoticesUpdate):
        await self.update(id=obj_in.id, obj_in=obj_in)
        return True

    async def do_delete(self, data_id: int):
        await self.remove(id=data_id)
        return True

    async def level_list(self,type:int):
        objs = await self.model.filter(type=type).values("id", "name")
        data = dict()
        for obj in objs:
            data[obj['id']] = obj['title']
        return data

notices_controller = NoticesController()
